<?php
/**
 * Created by PhpStorm.
 * User: shkj
 * Date: 2020/4/20
 * Time: 10:02
 */

namespace app\api\model;


use think\Model;
use think\Db;
class Banner extends Model
{
    public function img(){
        return $this->belongsTo('Image','img_id','id');
    }

    protected $autoWriteTimestamp = true;

    protected $createTime='create_time';
    protected $dateFormat='Y年m月d日';
    //开启自动设置
    protected $auto = [];
    protected $insert = ['create_tiame'];


    public function select(){
        $res = self::order('sort', 'asc')->all([],'img')->toArray();

        foreach ($res as $key => $value){

            foreach ($value['img'] as $k => $v){

                $value[$k]=$v;

                $res[$key] = $value;
            }
            unset($res[$key]['img']);
        }
        if($res){
            return_json(200,'查询成功',$res);
        }else{
            return_json(400,'查询失败');
        }
    }

    public function add($data)
    {

        $arr = array();
        $arr['images'] = $data['images'];

        $data['img_id'] = Db::name('image')->insertGetId($arr);//图片id

        $res = self::save($data);
        if($res){
            return_json(200,'添加轮播图成功');
        }else{
            return_json(400,'添加轮播图失败');
        }

    }

    public function del($id){
        $img = self::where('id',$id)->with('img')->find();

        $res = $img->together('img')->delete();

        if($res){
            return_json(200,'删除成功');
        }else{
            return_json(400,'删除失败');
        }
    }

    public function detail($id){

        $res = $this->where('id',$id)->with('img')->find()->toArray();
        foreach ($res['img'] as $k=>$v){
            $res[$k] = $v;
        }
        unset($res['img']);
        if($res){
            return_json(200,'查询成功',$res);
        }else{
            return_json(400,'查询失败');
        }
    }

    public function modify($id,$data)
    {
        $img = Image::where('images', $data['images'])->find();
        if ($img) {
            $data['img_id'] = $img['id'];
            $this->perform($id,$data);
        }
        else {
            $img = self::where('id',$id)->with('img')->find();

            if(!empty($img['img']['images'])){
                Image::where('images',$img['img']['images'])->delete();
            }

            $arr = array();
            $arr['images'] = $data['images'];

            $data['img_id'] = Db::name('image')->insertGetId($arr);//图片id
            $this->perform($id,$data);

        }

    }
    public function perform($id,$data){
        unset($data['images']);
        $res = self::where('id', $id)->update($data);
        if ($res) {
            return_json(200, '修改成功');
        } else {
            return_json(400, '修改失败');
        }
    }




}